<?php
date_default_timezone_set('Asia/Shanghai');
function getRootPath() {
	global $ROOT_PATH;
	$ROOT_PATH = dirname(dirname(__FILE__));
}
getRootPath();
include $ROOT_PATH . '/auto_load.php';

function getUser() {
	$tokenStr = isset($_COOKIE['token']) ? trim($_COOKIE['token']) : '';
	$arr = ObjectFinder::get("User")->decodeToken($tokenStr);
	if (!is_array($arr)) return false;
	return checkLogin($arr['id'], $arr['t']);
}

function checkLogin($id, $token){
	$userInfo = ObjectFinder::get("User")->getUserInfoById($id);
	if (!$userInfo)return false;
	return ($userInfo['token'] == $token) ? $userInfo : false;
}

function redirect($url){
    header('Location: '.$url);
    exit;
}

function echoAjax($result){
	if (empty($result) || !is_array($result)) {
		$result = Constants::$ERR_UNKNOWN;
	}
	echo json_encode($result);
	die();
}

function checkAuth() {
	global $userInfo;
	$userInfo = getUser();
	if (!$userInfo){
		$conf = ConfigUtil::getConfig('EXTERNALS');
		redirect($conf['baseUrl'].'/login.php');
	}
}

function getConfig() {
	global $conf, $destUrl;
	$conf = ConfigUtil::getConfig('EXTERNALS');
	if ($conf['domain'] == $_SERVER['SERVER_NAME']) {
		$destUrl = urlencode($_SERVER['SCRIPT_URI'].(empty($_SERVER['QUERY_STRING']) ? '' : '?'.$_SERVER['QUERY_STRING']));
	}
}
getConfig();
?>